package com.jy.appmarket.utils;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import android.content.Context;

import com.jy.app.market.idata.card.CardApkRecommend;
import com.jy.app.market.idata.data.Apk;
import com.jy.appmarket.AppMarketApplication;
import com.jy.appmarket.download.DownloadUtils;
import com.jy.appmarket.network.engine.ApkRecommendNetEngine;
import com.jy.appmarket.network.engine.BaseNetEngine;
import com.jy.appmarket.network.engine.cachestrategy.CacheStrategy;
import com.jy.appmarket.network.resultdata.ApkRecommendResult;
import com.jy.appmarket.network.task.NetTask;
import com.jy.appmarket.network.task.NetTask.NetTaskListener;

public class ApkRecommendHolder implements NetTaskListener {
	private static final String TAG = "ApkRecommendHolder";

	private static ApkRecommendHolder sInstance;

	private NetTask mNetTask;

	private CardApkRecommend mRecommend;
	private boolean mIsRunning = false;
	private WeakReference<ApkRecommendUpdateListener> mUpdateListener;

	public static ApkRecommendHolder getInstance() {
		if (sInstance == null) {
			synchronized (ApkRecommendHolder.class) {
				if (sInstance == null) {
					sInstance = new ApkRecommendHolder();
				}
			}
		}
		return sInstance;
	}

	public void updateRecommend(Context context, ApkRecommendUpdateListener listener) {
		mUpdateListener = new WeakReference<ApkRecommendHolder.ApkRecommendUpdateListener>(listener);
		updateRecommend(context);
	}

	public void updateRecommend(Context context) {
		if (mIsRunning) {
			return;
		}
		mIsRunning = true;
		mRecommend = null;
		Context ctx = context.getApplicationContext();
		ApkRecommendNetEngine engine = new ApkRecommendNetEngine(null);
		engine.setCacheStrategy(new CacheStrategy(true, CacheStrategy.THREE_HOUR));
		mNetTask = new NetTask(ctx, engine, 0);
		mNetTask.setListener(this);
		new Thread(mNetTask).start();
	}

	public CardApkRecommend getRecommend() {
		return getFilteredList(); // 去除本地已经安装和下载的
	}

	@Override
	public void onTaskRunSuccessful(int tag, BaseNetEngine engine) {
		mIsRunning = false;

		ApkRecommendResult data = (ApkRecommendResult) engine.getResultData();
		if (data.isOK()) {
			mRecommend = data.getApkRecommend();

			if (mUpdateListener != null && mUpdateListener.get() != null) {
				mUpdateListener.get().onRecommandFinished(getFilteredList());
			}
		}
	}

	@Override
	public void onTaskRunError(int tag) {
		mIsRunning = false;

		LogUtil.w(TAG, "failed to get recommend");
	}

	@Override
	public void onTaskRunCanceled(int tag) {
		mIsRunning = false;
		// ignore it
	}

	private List<Apk> getRandomApkList(List<Apk> apkList, int num) {
		if (apkList == null || num < 0 || apkList.size() <= num) {
			return apkList;
		}

		int size = apkList.size();
		boolean flag[] = new boolean[size];
		List<Apk> randomList = new ArrayList<Apk>();
		int n = 0;
		Random random = new Random();
		while (true) {
			int temp = random.nextInt(size);
			if (!flag[temp]) {
				if (n == num)
					break;
				flag[temp] = true;
				randomList.add(apkList.get(temp));
				n++;
			}
		}
		return randomList;
	}

	/*
	 * 获取客户端过滤后推荐列表 从服务器获取下来的推荐列表，去除客户端已经安装过的和在下载管理里面存在的apk，再随机获取1-3个做为推荐应用
	 */
	private CardApkRecommend getFilteredList() {
		if (mRecommend == null) {
			return null;
		}
		List<Apk> list = mRecommend.getApks();
		if (list == null || list.size() == 0) {
			return null;
		}

		// 去除掉安装过的和已经下载的apk
		ArrayList<Apk> filteredApkList = new ArrayList<Apk>();
		CardApkRecommend filteredRecomend = new CardApkRecommend();
		filteredRecomend.setType(mRecommend.getType());
		filteredRecomend.setTitle(mRecommend.getTitle());

		for (Apk apk : list) {
			// 获取apk的状态
			String pkgName = apk.getPackageName();
			if (PackageUtils.isPackageInstalled(AppMarketApplication.getApp(), pkgName)
					|| DownloadUtils.downloadExist(AppMarketApplication.getApp(), pkgName)) {
				continue;
			}
			filteredApkList.add(apk);
		}

		if (filteredApkList.size() == 0) {
			return null;
		}
		// 从过滤后的apk列表中随机选取3个做位推荐apk
		filteredRecomend.setApks(getRandomApkList(filteredApkList, 3));
		return filteredRecomend;
	}

	public interface ApkRecommendUpdateListener {
		void onRecommandFinished(CardApkRecommend recommend);
		// public void onError();
	}
}